package org.clockworkmages.games.anno1186;

import java.util.List;

import org.clockworkmages.games.anno1186.gui.GameUiUtil;
import org.clockworkmages.games.anno1186.model.GameMode;
import org.clockworkmages.games.anno1186.model.character.NonPlayerCharacter;
import org.clockworkmages.games.anno1186.model.situation.Situation;
import org.clockworkmages.games.anno1186.situations.combat.CombatSituation;

public class GameStateService {
	@Injected
	private GameDataService gameDataService;

	private GameState gameState = new GameState();

	public GameState getGameState() {
		return gameState;
	}

	public void removeCurrentSituation() {
		List<Situation> situationStack = gameState.getSituationStack();
		if (situationStack.size() > 0) {
			situationStack.remove(situationStack.size() - 1);
		}
	}

	public void addSituation(String situationId, boolean addToStack) {
		Situation situation = gameDataService.getGameData().getSituations()
				.get(situationId);
		if (situation == null) {
			GameUiUtil.logError("Invalid Situation reference \"" + situationId
					+ "\" in an Option (current Situation=\""
					+ gameState.getCurrentSituation().getId() + "\") .");
		}
		addSituation(situation, true);
	}

	public void addSituation(Situation situation, boolean addToStack) {
		List<Situation> situationStack = gameState.getSituationStack();
		if (!addToStack) {
			removeCurrentSituation();
		}
		gameState.setRecentlyAdded(gameState.getSituationStack().size());
		situationStack.add(situation);
		evictSituationCache(situationStack.size());
		gameState.setGameMode(GameMode.SITUATION);
	}

	/**
	 * Evict the cached values for one of the situations (as apparently a new
	 * Situation has been added that needs a fresh, empty cache).
	 */
	public void evictSituationCache(int stackSize) {
		gameState.getSituationCachedRandoms().remove(stackSize);
	}

	public void evictDailyCache() {
		gameState.getDailyCachedRandoms().clear();
	}

	public boolean isInCombat() {
		for (Situation situation : gameState.getSituationStack()) {
			if (situation instanceof CombatSituation) {
				return true;
			}
		}
		return false;
	}

	public NonPlayerCharacter getEnemy() {
		CombatSituation combatSituation = getCurrentCombatSituation();
		if (combatSituation != null) {
			return combatSituation.getEnemy();
		}
		return null;
	}

	public CombatSituation getCurrentCombatSituation() {
		for (Situation situation : gameState.getSituationStack()) {
			if (situation instanceof CombatSituation) {
				return ((CombatSituation) situation);
			}
		}
		return null;
	}

	public boolean isCombat() {
		return gameState.getCurrentSituation() instanceof CombatSituation;
	}

	/**
	 * Only to be used when loading a game or starting a new one.
	 * 
	 * @param gameState
	 */
	public void setGameState(GameState gameState) {
		this.gameState = gameState;
	}

}
